package com.download

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.InputStreamReader
import java.util.*

class MainActivity : AppCompatActivity() {

    lateinit var downLoadManager: DownLoadManager
    val apkDownloadUrls = Stack<String>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        downLoadManager = DownLoadManager.create(this)
        addUris()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.REQUEST_INSTALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.REQUEST_INSTALL_PACKAGES), 1001)
            }
        }

        downloadBackground.setOnClickListener {
            downLoadManager.downLoadFileBackground(apkDownloadUrls.pop())
        }

        downloadForeground.setOnClickListener {
            downLoadManager.downloadFile("", object : ProgressListener {
                override fun onProgressUpdate(totalBytes: Long, bytesRead: Long, done: Boolean) {
                    progressBar.progress = (bytesRead * 100f / totalBytes).toInt()
                }
            })
        }
    }

    private fun addUris() {
        var inputStream = assets.open("download_uris")
        val reader = InputStreamReader(inputStream)
        reader.readLines().forEach {
            apkDownloadUrls.push(it)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this.applicationContext, "权限已获取", Toast.LENGTH_SHORT).show()
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}
